package org.gruposp2p.proyectokarma.controller

import org.gruposp2p.cometd.KarmaMessageService;
import org.gruposp2p.proyectokarma.domain.Peer;
import org.gruposp2p.proyectokarma.domain.Document;
import org.gruposp2p.proyectokarma.domain.Vote;
import grails.plugins.springsecurity.Secured;
import org.hibernate.ObjectNotFoundException;
import grails.converters.JSON;

class UserController {

	def springSecurityService
    
	//def peerService;
    //def insertData = {render peerService.insertData();}
	
	def save = { }
	
	def show = {
		def userList = []
		def usersMap = new HashMap()
		if (params.ids?.size() > 0) {
			Peer.getAll(params.ids).collect {peer ->
				if (peer) userList << peer;
			}
			if (userList.size() == 0) {
				response.status = 404 //Not Found
				render message(code: 'proyectokarma.user.peerNotFound', args:[params.ids])
				return
			}
		} else {
			userList =  Peer.list(params)
			usersMap.numberOfUsersInSystem = Peer.count()
			usersMap.numberOfUsersInRequest = userList.count()
			usersMap.offset = params.offset
		}
		usersMap.peers = userList.collect {peer ->
			return [id: peer.id, email: peer.email, name:peer.name]
		}
		withFormat{
			html{
			  return [usersMap:usersMap]
			}
			json {
				render usersMap as JSON
			}
		}
	}
	
	def update = { }
	
	def delete = {
	   if (params.id) {
		   def peer = Peer.get(params.id)
		   if (peer) peer.delete()
		   else {
			   response.status = 404;
			   render message(code: 'proyectokarma.peer.deleteNotFound', args:[params.id])
			   return
		   }
		   response.status = 200;
		   render message(code: 'proyectokarma.peer.deleteOK', args:[params.id])
		   return
	   } else {
		   response.status = 400  //Bad Request
		   render message(code: 'proyectokarma.peer.deleteBadRequest')
		   return;
	   }
   }
	
	
	def getLoggedPeer = {
		def principal = springSecurityService.principal
		log.debug "principal: " + principal
		if (springSecurityService.isLoggedIn()) {
			response.status = 401
			render "ERROR. Unauthorized peer."
			return;
		}
		def peerDetails = springSecurityService.principal
		def peer = Peer.get(peerDetails.id).collect {peer ->
			return [id: peer.id, email: peer.email, name:peer.name]
		}
		render peer as JSON
	}
	
}
